<template>
	<view style="padding-bottom: 200rpx;">
    <public-loading></public-loading>
    <z-nav-bar id="nav" bgColor="#ffffff" :title="pageTitle"></z-nav-bar>
		<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
			<view class="cont-box">
				<view class="notice">
					企业认证须知：认证资料仅用于平台认证相关用途。
				</view>
				<view class="uploader">
					<z-upload-image limit="1" v-model:files="formData.businessLicenseUrl" action-type="custom">
						<view class="adrift">
							<image class="pic" src="http://www.xvopen.com/xiaoV/img1/business_license.png"></image>
							<view class="describe">请上传清晰的营业执照照片</view>
						</view>
					</z-upload-image>
				</view>
			</view>
			<view class="cont-box">
				<view class="uploader previous">
					<z-upload-image limit="1" v-model:files="formData.idCardFrontUrl" action-type="custom">
						<view class="adrift">
							<image class="icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
							<view class="describe">请上传清晰的身份证人像面照片</view>
						</view>
					</z-upload-image>
				</view>
				<view class="uploader">
					<z-upload-image limit="1" v-model:files="formData.idCardBackUrl" action-type="custom">
						<view class="adrift">
							<image class="icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
							<view class="describe">请上传清晰的身份证国徽面照片</view>
						</view>
					</z-upload-image>
				</view>
			</view>
			<view class="item-box combine">
				<view class="label">认证类型</view>
				<view class="panel">
					<z-data-select :disable="typeStore?true:false" :modelValue="modelValue" :localdata="selectDataList" @change="handleDataSelectChange">
						<view class="group">
							<view class="context">{{ baseInfo.authenticateTypeName }}</view>
							<uni-icons type="right" size="20"></uni-icons>
						</view>
					</z-data-select>
				</view>
			</view>
			<view class="item-box">
				<view class="form-item" v-if="baseInfo.authenticateTypeName=='店铺' || baseInfo.authenticateTypeName=='加盟店'">
					<view class="label" >店铺名称</view>
					<view class="cell">
						<uni-forms-item required name="storeName">
							<uni-easyinput
								v-model="formData.storeName" :placeholder="rules['storeName'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
        <view class="form-item" v-if="baseInfo.authenticateTypeName=='工厂'">
          <view class="label" >工厂名称</view>
          <view class="cell">
            <uni-forms-item required name="storeName">
              <uni-easyinput
                v-model="formData.storeName" :placeholder="rules['storeName'].rules[0].errorMessage"
                :placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
              />
            </uni-forms-item>
          </view>
        </view>
				<view class="form-item">
					<view class="label">企业名称</view>
					<view class="cell">
						<uni-forms-item required name="companyName">
							<uni-easyinput
								v-model="formData.companyName" :placeholder="rules['companyName'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
				<view class="form-item">
					<view class="label">统一社会信用代码</view>
					<view class="cell">
						<uni-forms-item required name="socialCreditCode">
							<uni-easyinput
								v-model="formData.taxNumber" :placeholder="rules['taxNumber'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
				<view class="form-item">
					<view class="label">法人信息</view>
					<view class="cell">
						<uni-forms-item required name="legalPerson">
							<uni-easyinput
								v-model="formData.legalPerson" :placeholder="rules['legalPerson'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
			</view>
			<view class="item-box">
				<view class="form-item">
					<view class="label">姓名</view>
					<view class="cell">
						<uni-forms-item required name="contactName">
							<uni-easyinput
								v-model="formData.contactName" :placeholder="rules['contactName'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
				<view class="form-item">
					<view class="label">电话</view>
					<view class="cell">
						<uni-forms-item required name="contactPhone">
							<uni-easyinput type="number" :maxlength="11"
                             :disabled="true"
								v-model="formData.contactPhone" :placeholder="rules['contactPhone'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
				<view class="form-item">
					<view class="label">身份证号码</view>
					<view class="cell">
						<uni-forms-item required name="idCardNumber">
							<uni-easyinput
                :disabled="true"
								v-model="formData.idCardNumber" :placeholder="rules['idCardNumber'].rules[0].errorMessage"
								:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
							/>
						</uni-forms-item>
					</view>
				</view>
        <view class="form-item">
          <view class="label">具体位置</view>
          <view class="cell" @click="chooseAddress()">
            <uni-forms-item required name="address">
              <uni-easyinput
                v-model="formData.address" :disabled="true" :placeholder="rules['address'].rules[0].errorMessage"
                :placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
              />
            </uni-forms-item>
          </view>
        </view>
			</view>
			<view class="bottom-btn-box">
				<main-button :color="'#fff'" :margin="'24rpx 0 0'" @click="submit">提交</main-button>
			</view>
		</uni-forms>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import {onLoad} from '@dcloudio/uni-app';
import { validatePhoneNumber, validateIdCard } from '@/utils/validate'
import { navigateBack } from '@/utils/navigator'
import { CustomPlaceHoder, delay } from '@/utils/common'
import {certificationAdd} from '@/api/pagesShop'
import {useCustomStores} from '@/utils/hook'
const {ShopStore:{shopInfo},userStore:{userInfo}} = useCustomStores()
const placeHolder = new CustomPlaceHoder({ fontSize: '32rpx', color: '#ccc', textAlign: 'right' })
const formRef = ref()
const app = getApp()
const authenticateTypeMap = {
	// 合作
	COOPERATION: 1,
	// 加盟
	JOIN: 2,
	// 物业店
	PROPERTY_SHOP: 3
}
const pageTitle = ref('自营店申请')
const typeStore= ref('') //自定义判断类型是什么店铺申请
const baseInfo = reactive({
	pageTitle: '自营店申请',
	authenticateTypeName: ''
})
const formData = reactive({
  storeName:'',
  businessLicenseUrl:"",
  idCardFrontUrl:"",
  idCardBackUrl:"",
  companyName: '',
  taxNumber:"",
  legalPerson:"",
  contactName:"",
  contactPhone:"",
  idCardNumber:"",
  address:"",
  certificationType:"SHOP",
})
if(userInfo.idCard){
  formData.idCardNumber = userInfo.idCard
}
if(userInfo.phonenumber){
  formData.contactPhone = userInfo.phonenumber
}
const rules = ref({
  storeName: {rules: [{ required: true, errorMessage: '请输入店铺名称' }]},
	companyName: {rules: [{ required: true, errorMessage: '请输入企业名称' }]},
  taxNumber: {rules: [{ required: true, errorMessage: '请输入统一社会信用代码' }]},
	legalPerson: {rules: [{ required: true, errorMessage: '请输入法人信息' }]},
  contactName: {rules: [{ required: true, errorMessage: '请输入姓名' }]},
  contactPhone: {
        rules: [
			{ required: true, errorMessage: '请输入电话' },
            { validateFunction: validatePhoneNumber }
		]
    },
  idCardNumber: {
        rules: [
			{ required: true, errorMessage: '请输入身份证号码' },
            // { validateFunction: validateIdCard }
		]
    },
	address: {rules: [{ required: true, errorMessage: '请选择位置' }]}
})
const selectDataList = ref([
	{ value: 'SHOP', text: '店铺' },
	{ value: 'FACTORY', text: '工厂' },
  { value: 'SHOP_JOIN', text: '加盟店' },
])
const  modelValue =ref("SHOP")
function chooseAddress(){
  uni.chooseLocation({
    success: function (res) {
      console.log('位置名称：' + res.name);
      console.log('详细地址：' + res.address);
      console.log('纬度：' + res.latitude);
      console.log('经度：' + res.longitude);
      formData.address = res.name
      formData.latitude = res.latitude
      formData.longitude = res.longitude
      formData.location = res.latitude+','+res.longitude
      // addressForm.latitude = res.latitude
      // addressForm.longitude = res.longitude
      // nextTick(()=>{
      //
      //   isAdd.value = true
      // })


    }
  });
}
const handleDataSelectChange = ({ text, value }) => {
	formData.certificationType = value
	baseInfo.authenticateTypeName = text
	// updatePageTitle()
}

const updatePageTitle = () => {
	if(formData.certificationType === 'SHOP') {
		baseInfo.pageTitle = '自营店申请'
	} else if(formData.authenticationType === authenticateTypeMap.JOIN) {
		baseInfo.pageTitle = '加盟店申请'
	} else if(formData.authenticationType === authenticateTypeMap.PROPERTY_SHOP) {
		baseInfo.pageTitle = '物业店申请'
	}
}

async function submit(){
	if (formRef.value) {
		const result = await formRef.value.validate().catch(() => false)
		if(result) {
			const tipsMap = {
        businessLicenseUrl: '请上传清晰的营业执照照片',
        idCardFrontUrl: '请上传清晰的身份证人像面照片',
        idCardBackUrl: '请上传清晰的身份证国徽面照片',
        certificationType: '请选择认证类型'
			}
			for(const key in tipsMap) {
				if(formData.hasOwnProperty(key) && !formData[key]) {
					return uni.showToast({ title: tipsMap[key], icon: 'none' })
				}
			}
			try {
				uni.showLoading({ title: '提交中', mask: true })
			await certificationAdd(formData)
        uni.showToast({ title:  '提交成功', icon: 'none' })
        delay().then(() => navigateBack())
			} catch (error) {
				uni.showToast({ title: error || '提交失败，请重试', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		}
	}
}

const initData = () => {
	const userInfo = uni.getStorageSync('userInfo')
	if(userInfo) {
		const { userId } = JSON.parse(userInfo)
		formData.userId = userId
	}
	const term = selectDataList.value.find(el => el.value === formData.authenticationType)
	term && handleDataSelectChange(term)
}

onLoad(({type,storeId})=>{
  if(type){
    typeStore.value = type
    pageTitle.value ="加盟店申请"
    modelValue.value = "SHOP_JOIN"
    formData.franchiseStoreId = shopInfo.storeId
    formData.franchiseStoreName = shopInfo.storeShortName
    /****这里传了参数代表加盟********/
    console.log('ShopStore111',shopInfo)
  }else {
    selectDataList.value = [
      { value: 'SHOP', text: '店铺' },
      { value: 'FACTORY', text: '工厂' },
    ]
  }
  // console.log('options',options)
})
</script>
<style lang="scss">
page {
	background-color: #fff;
}
input{
	text-align: right;
	color: #666;
}
.cont-box{
	padding: 20rpx 32rpx;
	border-bottom: 16rpx solid #F6F6F6;
	.notice{
		margin-bottom: 32rpx;
		width: 686rpx;
		height: 64rpx;
		line-height: 64rpx;
		text-align: center;
		border-radius: 12rpx;
		background-color: #E5F5FD;
		color: #1974C3;
	}
	.picture,.picture2{
		width: 686rpx;
		height: 339rpx;
		border: 1rpx dashed #999;
		border-radius: 16rpx;
		text{
			font-size: 24rpx;
			color: #999;
		}
	}
	.picture{
		margin: 32rpx 0 0;
		image{
			width: 100rpx;
			height: 65rpx;
			margin-bottom: 16rpx;
		}
	}
	.picture2{
		image{
			width: 52rpx;
			height: 44rpx;
			margin-bottom: 20rpx;
		}
	}
	.picture2:first-child{
		margin-bottom: 24rpx;
	}
}
.item-box{
	padding: 0 32rpx;
	border-bottom: 16rpx solid #F6F6F6;
	.item{
		height: 104rpx;
		text{
			color: #222;
			font-weight: bold;
			width: 270rpx;
		}
		view{
			color: #ccc;
		}
	}
	.form-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 104rpx;
		border-bottom: 1rpx solid #E5E5E5;
		font-size: 32rpx;
		color: #222;
		.uni-forms-item__error {
			top: calc(100% + 8rpx);
			left: unset;
			right: 0;
		}
		.uni-easyinput__content.is-disabled {
			background-color: unset !important;
			color: unset !important;
		}
	}
	.label {
		font-weight: bold;
		font-size: 32rpx;
		color: #222;
	}
	&.combine {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
}
.item-box:last-child{
	border-bottom: none;
}
.item-border{
	border-bottom: 1rpx solid #E5E5E5;
}
.place-class{
	color:#ccc;
	font-size:28rpx;
	text-align:right;
}
.mr-8{
	margin-right: 8rpx;
}
.uploader {
	height: 339rpx;
	border: 1rpx dashed #999;
	border-radius: 16rpx;
	&.previous {
		margin-bottom: 24rpx;
	}
	.adrift {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
		.icon {
			width: 52rpx;
			height: 44rpx;
		}
		.pic {
			width: 108rpx;
			height: 74rpx;
		}
		.describe {
			font-size: 24rpx;
			color: #999;
			margin-top: 12rpx;
			white-space: nowrap;
		}
	}
}
.panel {
	width: 200rpx;
	height: 104rpx;
	line-height: 104rpx;
	.group {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		color: #555;
		uni-icons {
			.uni-icons {
				color: #555;
				font-size: 28rpx !important;
			}
		}
	}
	::v-deep(.data-select) {
		.board {
			z-index: 999;
		}
	}
}
</style>
